package com.cashmama.market.api.domain.handler;

import com.alibaba.fastjson.JSONObject;
import com.cashmama.market.api.domain.oss.RetryOSSService;
import com.cashmama.market.api.domain.vo.user.AlgoTokenInfo;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.cashmama.market.api.infras.consts.RedisKeyConsts;
import com.cashmama.market.api.infras.utils.DateUtil;
import com.cashmama.market.api.infras.utils.HttpUtil;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.xjd.user.client.UserAuthSmsService;
import com.fqgj.xjd.user.client.request.UserAuthSms;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @program: market-api
 * @description algo360短信验证
 * @author: frank
 * @create: 2020-01-13 17:04
 **/
@Service
public class Algo360Handler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Algo360Handler.class);

    public static final String tokenUrl = "/o/token/";
    public static final String variablesUrl = "/api/v2/view/%s";
    public static final String variablesDetailUrl = "/get_data/%s";
    public static final String variablesPrioritizedUrl = "/v2/view/get_priority_variables/%s";
    public static final String scoreUrl = "/v2/view/get_score/%s";

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private RetryOSSService retryOSSService;
    @Autowired
    private UserAuthSmsService userAuthSmsService;

    public AlgoTokenInfo getAlgoToken(){
        Map headers = Maps.newHashMap();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        Map<String, String> params = Maps.newHashMap();
        params.put("client_id", apolloConfigUtil.getAlogo360ClientId());
        params.put("client_secret", apolloConfigUtil.getAlogo360ClientSecret());
        params.put("refresh_token", apolloConfigUtil.getAlogo360RefreshToken());
        params.put("grant_type", "refresh_token");
        String result = HttpUtil.postPage(apolloConfigUtil.getAlgo360Domain() + tokenUrl, params, headers);
        return JSONObject.parseObject(result, AlgoTokenInfo.class);
    }

    /**
     * 获取algo变量
     * @param cid
     */
    public void getVariablesData(String cid){
        packageRedisToken(cid);
        LOGGER.info("== algo360 get variables data begin cid:{} ==", cid);
        if(StringUtils.isNotEmpty(redisClient.get(RedisKeyConsts.ALOGO_360_ACCESS_TOKEN_KEY))){
            Map header = Maps.newHashMap();
            header.put("Authorization","Bearer " + redisClient.get(RedisKeyConsts.ALOGO_360_ACCESS_TOKEN_KEY));
            String result = HttpUtil.getPage(String.format(apolloConfigUtil.getAlgo360Domain() + variablesUrl, cid), null, header);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject resultObject = jsonObject.getJSONObject("result");
            LOGGER.info("== algo360 get variables status :{} ==", resultObject.getString("status"));
            //主要变量数据
            if(jsonObject != null && Objects.equals(resultObject.getString("status"),"success")){
                String filename = "algo360/variables/algo360_variables_" + cid + "_" + DateUtil.getDate(new Date()) + ".json";
                String dataUrl = retryOSSService.uploadFileWithRetry(filename, result);
                UserAuthSms userAuthSms = new UserAuthSms()
                        .setUserCode(cid)
                        .setStatus(1)
                        .setType(1)
                        .setVariablesUrl(dataUrl);
                userAuthSmsService.addUserAuthSms(userAuthSms);
                LOGGER.info("== algo360 get variables data success cid:{},url:{} ==", cid, dataUrl);
            }
            //详细变量报告数据
            String detailResult = HttpUtil.postPage(String.format(apolloConfigUtil.getAlgo360Domain() + variablesDetailUrl, cid), null, header);
            if(StringUtils.isNotEmpty(detailResult)){
                String filename = "algo360/variables/algo360_detail_" + cid + "_" + DateUtil.getDate(new Date()) + ".json";
                String dataUrl = retryOSSService.uploadFileWithRetry(filename, detailResult);
                UserAuthSms userAuthSms = new UserAuthSms()
                        .setUserCode(cid)
                        .setType(1)
                        .setStatus(1)
                        .setVariablesDetailUrl(dataUrl);
                userAuthSmsService.addUserAuthSms(userAuthSms);
                LOGGER.info("== algo360 get variables detail data success cid:{},url:{} ==", cid, dataUrl);
            }
        }
    }

    /**
     * 获取分数
     * @param cid
     */
    public void getVariableScore(String cid){
        packageRedisToken(cid);
        LOGGER.info("== algo360 get score begin cid:{} ==", cid);
        if(StringUtils.isNotEmpty(redisClient.get(RedisKeyConsts.ALOGO_360_ACCESS_TOKEN_KEY))){
            Map header = Maps.newHashMap();
            header.put("Authorization","Bearer " + redisClient.get(RedisKeyConsts.ALOGO_360_ACCESS_TOKEN_KEY));
            String scoreResult = HttpUtil.getPage(String.format(apolloConfigUtil.getAlgo360Domain() + scoreUrl, cid), null, header);
            LOGGER.info("== get algo360 score success, result :{} ==", scoreResult);
            JSONObject jsonObject = JSONObject.parseObject(scoreResult);
            if(jsonObject != null && Objects.equals(Boolean.TRUE, jsonObject.getBoolean("success"))){
                UserAuthSms userAuthSms = new UserAuthSms()
                        .setUserCode(cid)
                        .setType(1)
                        .setStatus(1)
                        .setScore(jsonObject.getInteger("score") == null ? 0 : jsonObject.getInteger("score"));
                userAuthSmsService.addUserAuthSms(userAuthSms);
                LOGGER.info("== algo360 get score success cid:{},score:{} ==", cid, jsonObject.getInteger("score"));
            }
        }
    }

    private void packageRedisToken(String cid){
        if(StringUtils.isEmpty(redisClient.get(RedisKeyConsts.ALOGO_360_ACCESS_TOKEN_KEY))){
            AlgoTokenInfo algoTokenInfo = this.getAlgoToken();
            if(algoTokenInfo != null && StringUtils.isNotEmpty(algoTokenInfo.getAccessToken())){
                redisClient.set(RedisKeyConsts.ALOGO_360_ACCESS_TOKEN_KEY, algoTokenInfo.getAccessToken(), 80000);
                LOGGER.info("algo360 set token success cid:{}, tokenInfo:{}", cid, JSONObject.toJSONString(algoTokenInfo.getAccessToken()));
            }
        }
    }

}
